import { authApi } from "../api/user";
import { useUserStore } from "../store/useUserStore";

import type { LoginParams, RegisterParams } from "../types/user";

export const userService = {
  async login(params: LoginParams) {
    try {
      useUserStore.getState().setLoading(true);
      useUserStore.getState().setError(null);

      const response = await authApi.login(params);

      if (response.code === 0) {
        useUserStore.setState({
          isAuthenticated: true,
          // user: {
          //   nickName: response.data.nickName,
          // },
          token: response.data.token,
          loading: false,
          error: null,
        });
      } else {
        throw new Error(response.message || "登录失败");
      }
    } catch (error) {
      useUserStore.setState({
        loading: false,
        error: error instanceof Error ? error.message : "登录失败",
      });
      throw error;
    }
  },

  async createAccount(params: RegisterParams) {
    try {
      useUserStore.getState().setLoading(true);
      useUserStore.getState().setError(null);

      const response = await authApi.register(params);
      if (response.code === 0) {
        // 注册成功后，自动登录
        await this.login({
          username: params.username,
          password: params.password,
        });
      } else {
        throw new Error(response.message || "注册失败");
      }
    } catch (error) {
      useUserStore.setState({
        loading: false,
        error: error instanceof Error ? error.message : "注册失败",
      });
      throw error;
    }
  },

  logout() {
    useUserStore.setState({
      isAuthenticated: false,
      user: null,
      token: null,
      error: null,
    });
  },
};
